<?php
/**
 * Created by cmb_weixin.master.
 * File: Wechat.php
 * User: xuewl
 * Date: 2017/12/13
 * Time: 02:50
 */

namespace app\api\controller\v1\user;

use app\api\controller\v1\Init;
use EasyWeChat\Factory;

class Wechat extends Init
{
    protected $model = null;

    protected $no_check_action = ['session_key', 'init'];

    public function _initialize() {
        parent::_initialize();
        $this->model = model('user/user', 'service');
    }

    /**
     * 根据 code 获取 session_key 登录态
     * 目的：获取 openid
     */
    public function init() {
        $session_key = $this->params['session_key'];
        //TODO:: 优化微信缓存方式
        $session = cache($session_key);
        if(!$session) {
            $config = config('wechat.mini_program');
            $miniProgram = Factory::miniProgram($config);
            $session = $miniProgram->auth->session($session_key);
            if($session['errcode']) {
                return $this->response($session['errmsg'], [], -77778);
            }
            $cache = $session['openid']."\t".$session['unionid'];
            cache($session_key, $cache);
            $openid = $session['openid'];
            $unionid = $session['unionid'];
        } else {
            list($openid, $unionid) = explode("\t", $session);
        }

        $info = [
            'openid' => (string) $openid,
            'unionid' => (string) $unionid,
            'avatar' => $this->params['userinfo']['avatarUrl'],
            'nickname' => $this->params['userinfo']['nickName'],
            'gender' => (int) $this->params['userinfo']['gender'],
            'province' => (string) $this->params['userinfo']['province'],
            'city' => (string)$this->params['userinfo']['city'],
            //'role' => 0,
        ];

        // 查找所属关系
        if($this->params['openid']) {
            $relation = model('user/user')->where(['openid' => $this->params['openid']])->find();
            if($relation['role'] == 1) {
                $info['distributor_id'] = $relation['id'];
                $info['customer_id'] = $relation['customer_id'];
            } elseif($relation['role'] == 2) {
                $info['distributor_id'] = 0;
                $info['customer_id'] = $relation['id'];
            }
        }

        $user = $this->model->regiser($info);

        if(!$user) {
            return $this->response($this->model->getError(), [], -20002);
        }
        return $this->response('初始化成功', $user);
    }
}
